
#include "FileHelper.h"
#include <fstream>


namespace FlameEngine
{
	void FileParser::ParseKeyValueFile(std::istream& iStream,std::map<std::string,std::string>& oResult,bool toLowerCase)
	{
		std::string whitespace(" \t\f\v\n\r");
		std::string line;

		while(std::getline(iStream,line))
		{
			std::size_t pos = line.find("=");
			if(pos != std::string::npos)
			{
				std::string keyStr = line.substr(0,pos);
				std::string valueStr = line.substr(pos+1);

				//trim whitespace
				size_t clipPos;
				clipPos = keyStr.find_first_not_of(whitespace);
				if(clipPos != std::string::npos)
					keyStr.erase(0,clipPos);

				clipPos = keyStr.find_last_not_of(whitespace);
				if(clipPos != std::string::npos)
					keyStr.erase(clipPos+1);

				if(keyStr.compare("") == 0)
					continue;

				clipPos = valueStr.find_first_not_of(whitespace);
				if(clipPos != std::string::npos)
					valueStr.erase(0,clipPos);

				clipPos = valueStr.find_last_not_of(whitespace);
				if(clipPos != std::string::npos)
					valueStr.erase(clipPos+1);

				if(toLowerCase)
				{
					for(int i=0;i<keyStr.size();i++)
					{
						char c = keyStr[i];
						if(c >= 'A' && c <= 'Z')
						{
							keyStr[i] = c - ('Z'- 'z');
						}
					}

					for(int i=0;i<valueStr.size();i++)
					{
						char c = valueStr[i];
						if(c >= 'A' && c <= 'Z')
						{
							valueStr[i] = c - ('Z'- 'z');
						}
					}
				}

				oResult[keyStr] = valueStr;
			}
		}
	}
}